package org.jb.coinche.server.user.impl;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import org.jb.coinche.client.user.LoginException;
import org.jb.coinche.client.user.UserService;
import org.jb.coinche.server.user.UserRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.servlet.SessionScoped;

/**
 * 
 * @author jeremie
 *
 */
@SessionScoped
public class UserServiceImpl implements UserService, Provider<String>, HttpSessionBindingListener {

	private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	private String user = null;
	private final UserRegistry registry;
	
	/**
	 * 
	 * @param registry
	 */
	@Inject
	public UserServiceImpl( UserRegistry registry ) {
		this.registry = registry;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.jb.coinche.client.user.UserService#connect(java.lang.String, java.lang.String)
	 */
	@Override
	public String connect(String name, String password) throws LoginException {
		
		if (name == null) {
			logger.debug("Autologing...");
			
			if (user != null) {
				logger.info("Autologing ok with user u={}", user );
				return user;
			}
			
			throw new LoginException();
		}
		
		registry.checkLogin(name, password);
		
		logger.info("Logging with user={}", name );
		
		user = name;
		
		return user;
	}

	/*
	 * (non-Javadoc)
	 * @see org.jb.coinche.client.user.UserService#disconnect()
	 */
	@Override
	public void disconnect() {
		user = null;
		// TODO : Suppression de la session HTTP
	}

	/*
	 * (non-Javadoc)
	 * @see com.google.inject.Provider#get()
	 */
	@Override
	public String get() {
		return user;
	}

	@Override
	public void valueBound(HttpSessionBindingEvent event) {
		logger.debug("Session bound");
	}

	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		if (user != null) {
			logger.debug("session unbound {}", user );
			
			registry.removeLogin(user);
		}	
	}

}
